<template>
  <el-row>
    <el-col :span="24">
      <ReceiptForm v-model="receipt"
                   :hidden-fields="hiddenFields" />
    </el-col>
    <el-col :span="24">
      <div class="footer">
        <el-button type="default"
                   @click="handleCancel">取消</el-button>
        <el-button type="primary"
                   :loading="loading"
                   @click="handleSubmit">确定</el-button>
      </div>
    </el-col>
  </el-row>
</template>
<script>
import { dialogFulfill } from '@tablra/fulfill/executors/RequestExecutor'
import { mapState, mapActions } from "vuex";
import axios from "axios";
export default {
  name: "BatchReceipt",
  props: {
    value: {
      type: Object,
      default: () => { }
    },
    data: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      hiddenFields: ["receiptDesc", "receiptSignTime", "syncUpAttachments"],
      receipt: {
        receiptDesc: "",
        receiptType: 0,
        receiptTime: this.$moment(new Date()).format("YYYY-MM-DD 23:59:00"),
        receiptSignTime: null
      },
      loading: false,
    }
  },
  computed: {
    ...mapState({
      batchReceiptId: (state) => state.batch.batchReceiptId,
    }),
    selection () {
      return this.value?.selection;
    },
    waybillIds () {
      return this.selection
        .filter(item => !item.signExceptionStatus)
        .map(({ waybillId }) => waybillId);
    },
    url () {
      return this.value?.url
    },
    idCountExceeded () {
      return this.selection?.length || 0
    },
    taskUrl () {
      return `/tenant/task/{id}`
    },
  },
  methods: {
    ...mapActions({
      setBatchReceiptId: "batch/setBatchReceiptId",
    }),
    async handleSubmit () {
      const response = await this.receipts()
      this.setBatchReceiptId(response)
      if (this.batchReceiptId) {
        this.$emit("cancel");
        const component = {
          taskUrl: this.taskUrl,
          count: this.idCountExceeded,
          name: `批量回单`,
          id: this.batchReceiptId || response
        }
        dialogFulfill.invoke(component)
      }
    },
    async receipts () {
      this.loading = true
      const { receiptTime, ...args } = this.receipt
      const receipt = {
        ...args,
        name: `批量回单`,
        waybillIds: this.waybillIds,
        receiptAt: receiptTime,
      }
      try {
        const response = await axios.post(this.url, receipt);
        if (response?.code === 0) {
          if (!response?.data) {
            this.loading = false
            this.$emit("confirm");
          }
          return response?.data;
        } else {
          this.loading = false;
          this.$message({ type: "error", message: response?.message });
        }
      } catch (error) {
        this.loading = false;
      }
    },
    handleCancel () {
      this.$emit("cancel");
    },
  }
}
</script>